package com.whg.demo.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.DispatcherType;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.UUID;

/**
 * @Author whg
 * @create 2022/12/2 17:06
 * @description：
 */
public class RequestInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(RequestInterceptor.class);

    private static final String UNIQUE_ID_NAME = "traceId";

    /**
     * 进入controller方法之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MDC.put(UNIQUE_ID_NAME, UUID.randomUUID().toString().replace("-", ""));
        if (request.getDispatcherType().equals(DispatcherType.ASYNC)) {
            return true;
        }
        if (logger.isInfoEnabled()) {
            StringBuilder sb = new StringBuilder("请求地址为：").append(request.getRequestURI()).append(" 请求参数为：");
            Enumeration<String> paramNames = request.getParameterNames();
            boolean hasParam = false;
            while (paramNames.hasMoreElements()) {
                hasParam = true;
                String paramName = (String) paramNames.nextElement();
                String value = request.getParameter(paramName);

                sb.append("&").append(paramName).append("=").append(value);
            }

            if (!hasParam) {
                logger.info("无");
            }else {
                logger.info(sb.toString().replaceFirst("&",""));
            }
        }

        // 获取请求IP地址
        String ipAddr = request.getHeader("X-Forwarded-For");
        if (ipAddr == null || ipAddr.trim().length() == 0) {
            ipAddr = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddr == null || ipAddr.trim().length() == 0) {
            ipAddr = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddr == null || ipAddr.trim().length() == 0) {
            ipAddr = request.getRemoteAddr();
        }

        request.setAttribute("ClientIP", ipAddr);

        return HandlerInterceptor.super.preHandle(request,response,handler);
    }

    /**
     * 调用完controller方法之后，视图渲染之前
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request,response,handler,modelAndView);
    }

    /**
     * 整个完成之后，通常用于资源清理
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.remove(UNIQUE_ID_NAME);
        HandlerInterceptor.super.afterCompletion(request,response,handler,ex);
    }
}
